import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { getOrders } from '../../services/payment';
import useAuthStore from '../../store/auth';

const Orders: React.FC = () => {
  const [orders, setOrders] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  
  const navigate = useNavigate();
  const isAuthenticated = useAuthStore(state => state.isAuthenticated);
  
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/login');
      return;
    }
    
    fetchOrders();
  }, [isAuthenticated]);
  
  const fetchOrders = async () => {
    try {
      setLoading(true);
      setError('');
      
      const response = await getOrders();
      
      if (response.code === 200) {
        setOrders(response.data.orders || []);
      } else {
        setError(response.message || '获取订单列表失败');
      }
    } catch (err: any) {
      setError(err.message || '获取订单列表失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };
  
  // 获取产品类型显示名称
  const getProductTypeName = (type: string) => {
    const typeMap: {[key: string]: string} = {
      'bazi_detail': '八字详解',
      'character_detail': '性格分析',
      'fengshui_detail': '风水分析',
      'fortune_detail': '运势预测',
      'name_analysis_detail': '姓名测算',
      'vip_membership': 'VIP会员',
      'wallet_recharge': '钱包充值'
    };
    
    return typeMap[type] || type;
  };
  
  // 获取订单状态显示名称
  const getOrderStatusName = (status: string) => {
    const statusMap: {[key: string]: string} = {
      'pending': '待支付',
      'paid': '已支付',
      'cancelled': '已取消',
      'refunded': '已退款',
      'failed': '支付失败'
    };
    
    return statusMap[status] || status;
  };
  
  // 获取订单状态显示样式
  const getOrderStatusStyle = (status: string) => {
    const styleMap: {[key: string]: string} = {
      'pending': 'bg-yellow-100 text-yellow-800',
      'paid': 'bg-green-100 text-green-800',
      'cancelled': 'bg-gray-100 text-gray-800',
      'refunded': 'bg-blue-100 text-blue-800',
      'failed': 'bg-red-100 text-red-800'
    };
    
    return styleMap[status] || 'bg-gray-100 text-gray-800';
  };
  
  // 模拟订单数据
  const mockOrders = [
    {
      orderNo: 'ORD202505180001',
      productType: 'bazi_detail',
      productName: '八字详解',
      amount: 0.1,
      status: 'paid',
      paymentType: 'wallet',
      createTime: '2025-05-18 08:00:00',
      payTime: '2025-05-18 08:01:00'
    },
    {
      orderNo: 'ORD202505170002',
      productType: 'character_detail',
      productName: '性格分析',
      amount: 0.1,
      status: 'paid',
      paymentType: 'wallet',
      createTime: '2025-05-17 15:30:00',
      payTime: '2025-05-17 15:31:00'
    },
    {
      orderNo: 'ORD202505160003',
      productType: 'vip_membership',
      productName: '月度VIP会员',
      amount: 9.9,
      status: 'paid',
      paymentType: 'wallet',
      createTime: '2025-05-16 10:15:00',
      payTime: '2025-05-16 10:16:00'
    },
    {
      orderNo: 'ORD202505150004',
      productType: 'wallet_recharge',
      productName: '钱包充值',
      amount: 50.0,
      status: 'paid',
      paymentType: 'alipay',
      createTime: '2025-05-15 09:20:00',
      payTime: '2025-05-15 09:22:00'
    }
  ];
  
  const displayOrders = orders.length > 0 ? orders : mockOrders;
  
  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
      </div>
    );
  }
  
  return (
    <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-4xl mx-auto">
        <div className="text-center mb-8">
          <h2 className="text-2xl font-bold text-gray-900">我的订单</h2>
        </div>
        
        {error && (
          <div className="text-red-500 text-center mb-6">
            {error}
          </div>
        )}
        
        {displayOrders.length === 0 ? (
          <div className="bg-white rounded-lg shadow-sm p-8 text-center">
            <p className="text-gray-500">暂无订单记录</p>
          </div>
        ) : (
          <div className="bg-white rounded-lg shadow-sm overflow-hidden">
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      订单号
                    </th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      商品
                    </th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      金额
                    </th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      状态
                    </th>
                    <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      创建时间
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {displayOrders.map((order) => (
                    <tr key={order.orderNo} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {order.orderNo}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm font-medium text-gray-900">{order.productName || getProductTypeName(order.productType)}</div>
                        <div className="text-xs text-gray-500">{order.paymentType === 'wallet' ? '钱包支付' : '支付宝'}</div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                        ¥{order.amount.toFixed(2)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${getOrderStatusStyle(order.status)}`}>
                          {getOrderStatusName(order.status)}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {order.createTime}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
        
        {/* 操作按钮 */}
        <div className="mt-8 flex justify-center">
          <button
            onClick={() => navigate('/wallet')}
            className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
          >
            返回钱包
          </button>
        </div>
      </div>
    </div>
  );
};

export default Orders;
